package org.shan.hangtian.server.handler;

import com.mlnx.common.utils.MyLog;

import org.shan.hangtian.server.session.SessionManager;
import org.shan.hangtian.tp.HangtianPacket;

import java.util.List;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;

/**
 * Created by amanda.shan on 2020/10/5.
 */
public class DataDecode extends ByteToMessageDecoder {

    MyLog log = MyLog.getLog(getClass());

    enum State {
        HEAD, CONTANT
    }

    private State state = State.HEAD;
    private int matchHeadIndex;
    private int length = 3;

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {

//        log.debug("收到的数据大小:{}", in.readableBytes());

//        int len = in.readableBytes();
//        byte[] bytes = new byte[len];
//        in.readBytes(bytes);

        while (true) {
            switch (state) {
                case HEAD:
                    if (matchHead(in)) {
                        state = State.CONTANT;
                    } else {
                        return;
                    }
                case CONTANT:
                    log.debug("识别出包头");
                    if (in.isReadable(length)) {

                        byte[] bytes = new byte[length];

                        in.readBytes(bytes);
                        HangtianPacket hangtianPacket = new HangtianPacket();
                        hangtianPacket.decode(bytes);

                        if (hangtianPacket.getRunMode() != null) {
                            log.debug("收到模式:{}", hangtianPacket.getRunMode());
                            SessionManager.getInstance().modeChange(hangtianPacket.getRunMode());
                        }else{
                            log.error("无法解析收到的模式");
                        }

                        state = State.HEAD;
                        break;
                    } else {
                        return;
                    }
                default:
                    return;
            }
        }

    }

    private boolean matchHead(ByteBuf buf) {

        while (buf.isReadable()) {
            if (matchHeadIndex == HangtianPacket.Heads.length) {
                matchHeadIndex = 0;
                return true;
            }
            byte b = buf.readByte();
            if (b == HangtianPacket.Heads[matchHeadIndex]) {
                matchHeadIndex++;
            } else if (b == HangtianPacket.Heads[0]) {
                matchHeadIndex = 1;
            } else {
                matchHeadIndex = 0;
            }
        }
        return false;
    }
}
